package cn.itcast.gateway.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * TODO
 *
 * @Authot mr.wu
 * @Date 2025/1/3 15:59
 */
@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取请求参数
        MultiValueMap<String, String> valueMap = exchange.getRequest().getQueryParams();
        // 2.获取参数中的 authorization 参数
        String auth = valueMap.getFirst("authorization");
        // 3.校验
        if ("admin".equals(auth)){

            //放行
            return chain.filter(exchange);
        }
        // 4.拦截
        // 4.1 设置状态码
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        // 4.2 结束请求
        return exchange.getResponse().setComplete();
    }
}
